 struct ListNode {
      int val;
    ListNode *next;
      ListNode() : val(0), next(nullptr) {}
      ListNode(int x) : val(x), next(nullptr) {}
      ListNode(int x, ListNode *next) : val(x), next(next) {}
 };
 
class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        ListNode* newhead = head;
        if(head->next == nullptr)
        {
            return nullptr;
        }
        ListNode* fast = head;
        ListNode* cur = head;
        ListNode* prev = nullptr;
        ListNode* next = nullptr;

        while (--n) {
            fast = fast->next;
        }
        while (fast->next) {
            prev = cur;
            cur = cur->next;
            fast = fast->next;
            if(cur->next)
                next = cur->next;
        }

        if(cur == fast)
        {
            prev->next = nullptr;
        }
        else if(prev == nullptr)
        {
            newhead = newhead->next;
        }
        else
        {
            prev->next = next;
        }

        return newhead;
        
    }
};